'use strict';
var AV     = require('leanengine');
var moment = require('moment');
var router = require('express').Router();
var url    = require('url');
var fs = require('fs');
var busboy = require('connect-busboy');
var qiniu = require('./qiniu.js');
var ComSet = require('../comset');
var ErrorCode = require('./err');
//公共函数
var ComFunc = require('../comfunc');
var User      = require('./api_users');

// 文件上传
function uploadFile (req, callback) {
  var arg = url.parse(req.url, true).query;
  if (req.busboy) {
    var base64data = [];
    var param={};
    var pubFileName = '';
    var pubMimeType = '';
        req.busboy.on('file', (fieldname, file, fileName, encoding, mimeType) => {
        var buffer = '';
              pubFileName = fileName;
              pubMimeType = mimeType;
              file.setEncoding('base64');
              file.on('data', function(data) {
                  buffer += data;
              }).on('end', function() {
                  base64data.push(buffer);
              });
        }).on('field',function(params,val){
           const data = {};
           param[params] = val;
        }).on('finish', function() {
        if (!param.token) {
          let resdata ={
            code:"-1",
            message:"请登录"
          }
          return callback(resdata)
        }
        User.getUserId(param.token,function(err,userresult){
          if(err){
            return callback(err)
          }else{
            try {
              //新建本地文件名字，并保存到本地
              var d = new Date();
              var baseUrl = './public/upload/'+ d.getFullYear()+"-"+(d.getMonth()+1)+"-"+d.getDate();
              if (!fs.existsSync(baseUrl)) {
                 fs.mkdirSync(baseUrl);
              }
              var filepath = baseUrl+'/'+ComFunc.getTimeStamp()+Math.round(new Date() / 1000)+pubFileName ;
              fs.writeFile(filepath,base64data[0],{encoding:"base64"},function(err){
                  if(!err){
                          //将文件上传到七牛云存储
                          qiniu.uploadFile(filepath,filepath,function(result){
                            //上传成功之后将本地文件删除
                            fs.unlink(filepath, function(err){
                                 if(err){
                                      throw err;
                                 }
                                 console.log('文件:'+filepath+'删除成功！');
                              })
                            var data = ComSet.qiniuBaseUrl+result.key;
                            var datas = {
                              // result:result,
                              message:"success",
                              code:"1",
                              data:{
                                url:data
                              }
                            }
                            // var resdata = {
                            //     url:data,
                            //     uploaded: 1,   //写死的
                            //     fileName:pubFileName
                            // }
                            return callback(datas);
                         })
                  }else{
                       return callback(ErrorCode.false);
                  }
              })    
            } catch (error) {
              console.log('uploadFile -:' + error);
              return callback(ErrorCode.false);
            }
          }
        })
        // getuserid_end
      })
      req.pipe(req.busboy);
  } else {
    console.log('uploadFile - busboy undefined.');
    return callback(ErrorCode.false);
  }
};

//获取ip地址
var getClientAddress=function(req) {
  return (req.headers['x-forwarded-for'] || '').split(',')[0] 
  || req.connection.remoteAddress;
};

module.exports.uploadFile=uploadFile;